<template>
	<view>
		<view class="u-demo-block__content" style="margin: 15rpx;">
			<!-- <u-navbar back-text="返回" title="处理列表数据" @leftClick="goToPre()"></u-navbar> -->
			<view class="u-page__tag-item">
				<u-search placeholder="输入合同号查询" 
					v-model="contractCode" 
					@custom="customQuery" 
					@search="customQuery"></u-search>
			</view>
		</view>
		<view>
			<u-tabs
				@click="tabClick"
				:list="tabList"
				lineWidth="58"
				lineColor="#f56c6c"
				:activeStyle="{
					color: '#303133',
					fontWeight: 'bold',
					transform: 'scale(1.05)'
				}"
				:inactiveStyle="{
					color: '#606266',
					transform: 'scale(1)'
				}"
				itemStyle="padding-left: 15px; padding-right: 15px; height: 40px;">
				<view slot="right" style="padding-left: 10px;padding-right: 10px;" 
						@tap="tabSlotClick" 
						v-if="tabActive!='未完工'">
					<u-icon 
						name="https://cdn.uviewui.com/uview/demo/calendar/10.png"
						size="30" bold></u-icon>
				</view>
				<view slot="right" style="padding-left: 10px;padding-right: 10px;" 
					v-else>
					<u-button class="btn submit" 
						shape="circle" 
						size="small" 
						type="warning" 
						:text="stationBtnText"
						@click="stationOptionUpdate"></u-button>
				</view>
			</u-tabs>
		</view>
		<view class="card-container" v-if="workOrderList.length > 0">
			<view v-for="(work, index) in workOrderList"
			class="card-wrap"
			:key="index"
			:class="{ 'card-wrap-selected': work.selectedCard === 1 }"
			@click="selectCard(work)">
				<view class="card-item">
					产品名称：<u-tag :text="work.bomName" plain size="mini" type="warning"></u-tag>
				</view>
				<view class="card-item">
					规格型号：<u-tag :text="work.bomStandard" plain></u-tag>
				</view>
				<view class="card-item">
					工单号：
					<u--text :text="work.workerorderCode" type="info"></u--text>
				</view>
				<view class="card-item">
					订单合同：
					<u--text :text="work.contractCode" style="color: aquamarine;"></u--text>
				</view>
				<view class="card-item" v-if="tabActive=='已完工'">
					报工日期：
					<u--text :text="work.createDate" type="info"></u--text>
				</view>
				<view class="card-item" v-if="tabActive=='已完工'">
					报工站点：<u--text :text="work.stationName" type="info"></u--text>
				</view>
				<view class="card-item">
					<u--text type="primary" :bold="trueValue" size="14" 
					:text="`工单数: ${work.workorderNum}`"></u--text>
					<u--text type="success" :bold="trueValue" size="14" 
					:text="`已累计报工数: ${work.hasCompletionNum?work.hasCompletionNum:0}`"></u--text>
				</view>
				<u-line v-if="tabActive=='已完工'"></u-line>
				<view class="card-item" v-if="tabActive=='已完工'">
					<u--text type="primary" :bold="!trueValue" size="14" :text="`班次: ${work.shiftTypeName}`"></u--text>
					<u--text type="success" :bold="!trueValue" size="14" :text="`良品数: ${work.goodNum}`"></u--text>
					<u--text type="success" :bold="!trueValue" size="14" :text="`不合格数: ${work.ungoodNum}`"></u--text>
				</view>
				<view class="card-item-single" v-if="tabActive=='未完工'">
					<u-cell :border="trueValue" title="剩余未完成:">
						<u-number-box slot="right-icon" v-model="work.remainingCompletionNum" inputWidth="60" :min="0" :disabled="trueValue"></u-number-box>
					</u-cell>
					<u-cell :border="!trueValue" title="今日良品数:">
						<u-number-box slot="right-icon" v-model="work.todayCompletionReq" inputWidth="60" :min="0" :max="work.remainingCompletionNum"></u-number-box>
					</u-cell>
					<u-cell :border="!trueValue" title="今日不合格数:">
						<u-number-box slot="right-icon" v-model="work.ungoodNumReq" inputWidth="60" :min="0" :max="work.remainingCompletionNum - work.todayCompletionReq"></u-number-box>
					</u-cell>
				</view>
			</view>
		</view>
		<view v-if="this.workOrderList.length == 0" style="padding-top: 60px;">
			<u-loading-icon text="数据加载中" textSize="18" color="#19be6b" :show="loadingShow"></u-loading-icon>
			<u-empty mode="data" v-if="!loadingShow"></u-empty>
		</view>
		<FloatMuitlButton @left-click="handleLeftClick" @right-click="handleRightClick"></FloatMuitlButton>
		
		<SumitInfo 
			:show="submitInfoShow"
			:total="submitTotal"
			:station="station"
			:ungoodTotal="submitUngoodTotal"
			:preSubmitList="completionWorkList"
			@close="submitInfoShow = false"
			@submit="submitReally"></SumitInfo>
			
		<StationOptions 
			:show="stationOptionShow"
			@close="stationOptionShow = false"
			@submit="saveStationOption"></StationOptions>
		
		<u-calendar 
			@confirm="calendarConfirm"
			@close="calendarClose"
			title="已报工日期选择查询"
			:show="showDate" 
			mode="multiple" 
			monthNum="5" 
			:minDate="minDate" 
			:defaultDate="defaultDateMultiple">
		</u-calendar>
		
		<u-toast ref="uToast" duration="3000" />
	</view>
</template>

<script>
const d = new Date();
const year = d.getFullYear();
let month = d.getMonth() + 1;
month = month < 10 ? `0${month}` : month;
const date = d.getDate();

import FloatMuitlButton from '@/components/button/FloatMuitlButton';
import SumitInfo from '@/components/definedialog/submitInfo';
import StationOptions from '@/components/definedialog/stationOptions';
import * as submitApi from '@/api/work/worksubmit';
import storage from '@/utils/storage';

export default {
	components: {
		FloatMuitlButton,
		SumitInfo,
		StationOptions,
	},
	data() {
		return {
			workOrderList: [],
			completionWorkList: [],
			loadingShow: false,
			submitInfoShow: false,
			submitTotal: 0,
			submitUngoodTotal: 0,
			tabList: [{
				name: '未完工',
			}, {
				name: '已完工',
			}],
			show: false,
			// 查询参数，比如：合同号
			contractCode: "",
			submitDateList: [],
			checked: ["选中"],
			tabActive: "未完工",
			// u-checkbox-group的v-model绑定的值如果设置为某个checkbox的name，就会被默认选中
			checkboxValue1: [],
			selectedCard: null, // 选中的卡片ID
			trueValue: true,
			// 日期弹窗
			showDate: false,
			minDate: `${year}-${month}-${date-30}`,
			defaultDateMultiple: [],
			
			stationOptionShow: false,
			stationBtnText: "选择站点",
			
			isVisible: true,
			clickCount: 0,
				
			station: null,
			
			loadStatus: "loadmore",
			pageNum: 1,
			totalPageCount: 0,
		}
	},
	onLoad (options) {
		// TODO 临时测试数据
		this.defaultDateMultiple.push(`${year}-${month}-${date-1}`);
		this.defaultDateMultiple.push(`${year}-${month}-${date}`);
		
		const station = storage.get('STATION_0');
		if (station) {
			console.log("站点:", station);
			this.stationBtnText = `站点(${station.stationName})`;
			this.station = station;
			this.queryWaitingCompletionList();
		} else {
			// 如果第一次未选择站点，先选择站点
			this.stationOptionShow = true;
		}
	},
	created() {
		const station = storage.get('STATION_0');
		if (station) {
			this.station = station;
		} 
	},
	methods: {
		onReachBottom() {
			console.log("onReachBottom", this.pageNum, this.totalPageCount);
			if (this.pageNum > this.totalPageCount) {
				console.log("已经加载到最多了");
				return;
			}
			this.pageNum ++;
			if (this.tabActive === "未完工") {
				this.queryWaitingCompletionList();
			} else {
				this.queryHasCompletionList();
			}
		},
		handleLeftClick() {
		 this.floatOnclick();
		},
		handleRightClick() {
		 this.submitCompletion();
		},
		stationOptionUpdate() {
			console.log("stationOptionShow:", this.stationOptionShow);
			this.stationOptionShow = true;
		},
		saveStationOption(station) {
			console.log("saveStationOption:", station);
			// 缓存10天
			storage.set('STATION_0', station, 864000);
			this.stationBtnText = `站点(${station.stationName})`;
			this.stationOptionShow = false;
			this.station = station;
			this.customQuery();
		},
		// TODO 连接后台服务
		queryWaitingCompletionList() {
			this.loadingShow = true;
			// this.workOrderList = [];
			submitApi.getWaitingCompletionList({
				pageNum: this.pageNum,
				stationId: this.station.stationId,
				contractCode: this.contractCode,
			}).then(res => {
				console.log("查询待报工的订单数据成功:", res);
				if(res && res.rows) {
					const result = res.rows || [];
					for (let item of result) {
						this.workOrderList.push(item);
					}
				}
				this.loadingShow = false;
				
				// 分页查询
				this.totalPageCount = res.totalPageCount || 0;
				if (this.pageNum >= this.totalPageCount) {
					this.loadStatus = 'nomore';
				} else {
					this.loadStatus = 'loading';
				}
			}).catch(err => {
				console.error("查询待报工的订单数据异常:", err);
				this.loadingShow = false;
			});
		},
		queryHasCompletionList() {
			this.loadingShow = true;
			//this.workOrderList = [];
			submitApi.getCompletionList({
				pageNum: this.pageNum,
				stationId: this.station.stationId,
				contractCode: this.contractCode, 
				submitDateList: this.submitDateList,
			}).then(res => {
				console.log("查询已报工的订单数据成功:", res);
				if(res && res.rows) {
					const result = res.rows || [];
					for (let item of result) {
						this.workOrderList.push(item);
					}
				}
				this.loadingShow = false;
				
				// 分页查询
				this.totalPageCount = res.totalPageCount || 0;
				if (this.pageNum >= this.totalPageCount) {
					this.loadStatus = 'nomore';
				} else {
					this.loadStatus = 'loading';
				}
			}).catch(err => {
				console.error("查询已报工的订单数据异常:", err);
				this.loadingShow = false;
			});
		},
		tabClick(e){
			console.log("tabClick,", e);
			this.tabActive = e.name;
			this.customQuery();
		},
		customQuery() {
			this.workOrderList = [];
			this.pageNum = 1;
			if(this.tabActive === "未完工") {
				this.queryWaitingCompletionList();
			} else if (this.tabActive === "已完工") {
				this.queryHasCompletionList();
			}
		},
		tabSlotClick(item) {
			console.log('item', item);
			this.showDate = true;
		},
		selectCard(work) {
			console.log("work=", work);
		},
		floatOnclick(e) {
			// TODO 扫描按钮事件
			console.log("扫描按钮事件:", e);
			// alert("正在打开飞书摄像头扫码");
			let _this = this;
			window.h5sdk.ready(() => {
				tt.scanCode({
					scanType: ["barCode", "qrCode", "datamatrix", "pdf417"],
					barCodeInput: true,
					success(res) {
						console.log("扫描返回:", res);
						// alert("成功:"+JSON.stringify(res));
						_this.contractCode = res.result;
						_this.customQuery();
					},
					fail(res) {
						console.log(`scanCode fail:`, res);
						alert("失败:"+JSON.stringify(res));
					},
				});
			});
		},
		calendarConfirm(selectedItem) {
			console.log("日历选中", selectedItem);
			this.submitDateList = selectedItem;
			this.showDate = false;
			this.defaultDateMultiple = selectedItem;
			this.customQuery();
		},
		calendarClose() {
			this.showDate = false;
		},
		open() {
			// console.log('open');
			document.body.style.overflow = 'hidden'; // 禁用背景页面滚动
		},
		close() {
			this.show = false
			// console.log('close');
			document.body.style.overflow = ''; // 恢复背景页面滚动
		},
		reset() {
		},
		submitCompletion() {
			if (!this.workOrderList || this.workOrderList.length == 0) {
				this.$refs.uToast.error(`报工工单数据为空，提交失败`);
				return;
			}
			// 开始计算进行提交数据是否存在异常
			this.completionWorkList = [];
			let total = 0;
			let unGoodTotal = 0;
			for(let item of this.workOrderList) {
				if (!item.todayCompletionReq || item.todayCompletionReq <= 0) {
					continue;
				}
				this.completionWorkList.push({
					contractCode: item.contractCode,
					bomName: item.bomName,
					bomStandard: item.bomStandard,
					workerorderCode: item.workerorderCode,
					bomCode: item.bomCode,
					todayCompletionReq: item.todayCompletionReq,
					ungoodNumReq: item.ungoodNumReq,
				});
				total += item.todayCompletionReq;
				unGoodTotal += item.ungoodNumReq;
			}
			if (this.completionWorkList.length == 0) {
				this.$refs.uToast.error(`今日报工数都是 0，请先输入`);
				return;
			}
			
			this.submitInfoShow = true;
			this.submitTotal = total;
			this.submitUngoodTotal = unGoodTotal;
		},
		submitReally(callItem) {
			this.submitInfoShow = false;
			for(let item of this.completionWorkList) {
				item.remark = callItem.errMessage;
				item.stationId = callItem.stationId;
				item.stationName = callItem.stationName;
			}
			console.log("报工真正提交:", this.completionWorkList);
			submitApi.newSubmitStationDay(this.completionWorkList).then(res => {
				// 提交结果
				console.log("报工真正提交成功",  res);
				if (res.code == 200) {
					this.$refs.uToast.success(`今日报工提交成功,完工数:${this.submitTotal}`);
					this.completionWorkList = [];
					this.customQuery();
				} else {
					this.$refs.uToast.error(`今日报工提交失败,${res.msg}`);
				}
			}).catch(err => {
				// 提交异常
				console.error("报工真正提交发生异常", err);
			});
		},
		goToPre() {
			console.log("返回主页");
			uni.reLaunch({ url: '/pages/work/index' });
		},
	}
}
</script>

<style lang="scss" scoped>
/deep/.u-cell__body {
  // padding: 6px 0 !important;
  display: flex;
  flex-direction: row;
  box-sizing: border-box;
  padding: 6px 8px !important;
  font-size: 15px;
  color: #303133;
  align-items: center;
}
.card-container{
	width: 100%;
	min-height: 100%;
	box-sizing: border-box;
	padding: 16rpx;
	background-color: #ECECEC;
}
.card-wrap{
	padding: 12rpx;
	border-radius: 12rpx;
	margin-bottom: 12rpx;
	background-color: #FFF;
	border: 1px solid #ddd; /* 默认边框 */
	transition: background-color 0.3s, border-color 0.3s;
	.card-item{
		display: flex;
		align-items: center;
		font-size: 28rpx;
		padding-left: 6rpx;
		padding-bottom: 18rpx;
		color: #40485d;
	}
	.card-item-txt{
		flex:1;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}
}
.card-btns{
	display: flex;
	justify-content: space-between;
	align-items: center;
}
.card-btns uni-button {
  flex: 1;
  margin: 0 5px; /* 调整按钮间距 */
}
.card-wrap-selected {
  border-color: #007bff; /* 选中状态的边框颜色 */
  background-color: #e7f0ff; /* 选中状态的背景颜色 */
}
.gridcell {
  border: 1px solid #ddd;
  text-align: center;
  line-height: 20px; /* Adjust line-height to match height */
  height: 30px; /* Set height to 20px */
  background-color: #f9f9f9;
  font-size: 14px; /* Adjust font-size to fit */
  overflow: hidden; /* Hide overflow if text is too large */
}
.card-item-single{
	border-radius: 6rpx;
	background-color: #FFF;
	border: 1px solid #ddd; /* 默认边框 */
	transition: background-color 0.3s, border-color 0.3s;
	align-items: left;
	font-size: 30rpx;
	color: #40485d;
}

.submit {
	// background-color: #007cff;
	text-align: center;
	margin: 5px 15px 5px 5px;
}

.demo-layout {
	height: 25px;
	border-radius: 4px;
}
.bg-purple {
	background: #CED7E1;
}
.bg-purple-light {
	background: #e5e9f2;
}
</style>
